﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using VSSAHT.DataAccess;
using VSSAHT.Transfer;
using VSS_AHT.Reports;
using CrystalDecisions.CrystalReports.Engine;
using VSS_AHT.ReportForms;
using VSS_AHT.Properties;
using CatelCrm.Data;
using CatelCrm.Helpers;
using System.IO;
using VSSAHT;
namespace VSS_AHT.Forms
{
    public partial class FormScaleTicketList : BaseForm
    {

        #region Singleton Members
        private static volatile FormScaleTicketList instance;
        private static object syncRoot = new Object();
        private DataTable table = new DataTable("Sheet1");

        public static FormScaleTicketList Instance
        {
            get
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new FormScaleTicketList();
                }

                return instance;
            }
        }
        #endregion

        #region Vailables
        ScaleTicketDTO _scale = new ScaleTicketDTO();
        IList<ScaleTicketDTO> _scaleList;
        ScaleTicketDataAccess _dataAccess = new ScaleTicketDataAccess();
        private string _data = String.Empty;
        private readonly SettingApp _settings = new SettingApp();
        #endregion

        #region Ctors
        public FormScaleTicketList()
        {
            InitializeComponent();
            Initialize();
        }
        public void Initialize()
        {
            this.MaximizeBox = true;
            this.groupBoxExportOrder.Visible = false;

        }
        
        #endregion

        #region Methods
        private void btnSearch_Click(object sender, EventArgs e)
        {
            this.Search();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            this.fromdateScale.DateTime = DateTime.Now;
            this.toDateScale.DateTime = DateTime.Now;
            this.txtCustomer.Text = "";
            this.txtItem.Text = "";
            this.txtLocation.Text = "";
            this.txtModelVehicleCode.Text = "";
            this.txtRequireNumber.Text = "";
            this.txtVehicleID.Text = "";
            this.Search();
            
        }
        void btnExportExcel_Click(object sender, EventArgs e)
        {
            if (Common.ShowYesNoQuestion("Bạn có muốn xuất Excel mã phiếu yêu cầu theo từng nhóm khách hàng?"))
            {


                DateTime inTime;
                TimeSpan ti;
                DateTime outTime;
                TimeSpan to;
                int fromhour = 0;
                int tohour = 0;
                if (txtFromHour.Text.Length == 0 || txtToHour.Text.Length == 0)
                {
                    MessageBox.Show("Bạn phải nhập từ giờ nào đến giờ nào.","Lỗi",MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return;
                }
                if (Int32.Parse(txtFromHour.Text) > 24 || Int32.Parse(txtToHour.Text) > 24)
                {
                    MessageBox.Show("Thời gian không được vượt quá 24.", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                fromhour = Int32.Parse(txtFromHour.Text);
                tohour = Int32.Parse(txtToHour.Text);
                IList<ScaleTicketDTO> list;
                inTime = fromdateScale.DateTime;
                ti = new TimeSpan(fromhour, 0, 0);
                inTime = inTime.Date + ti;
                outTime = toDateScale.DateTime;
                to = new TimeSpan(tohour, 59, 59);
                outTime = outTime.Date + to;
                this.Search(inTime, outTime);
                //switch ((short)radioGroup1.EditValue)
                //{
                //    case 0:
                //        inTime = fromdateScale.DateTime;
                //        ti = new TimeSpan(0, 0, 0);
                //        inTime = inTime.Date + ti;
                //        outTime = toDateScale.DateTime;
                //        to = new TimeSpan(7, 0, 0);
                //        outTime = outTime.Date + to;
                //        this.Search(inTime, outTime);
                //        break;
                //    case 1:
                //        inTime = fromdateScale.DateTime;
                //        ti = new TimeSpan(7, 0, 1);
                //        inTime = inTime.Date + ti;
                //        outTime = toDateScale.DateTime;
                //        to = new TimeSpan(12, 0, 0);
                //        outTime = outTime.Date + to;
                //        break;
                //    case 2:
                //        inTime = fromdateScale.DateTime;
                //        ti = new TimeSpan(12, 0, 1);
                //        inTime = inTime.Date + ti;
                //        outTime = toDateScale.DateTime;
                //        to = new TimeSpan(17, 0, 1);
                //        outTime = outTime.Date + to;
                //        this.Search(inTime, outTime);
                //        break;
                //    case 3:
                //        inTime = fromdateScale.DateTime;
                //        ti = new TimeSpan(17, 0, 1);
                //        inTime = inTime.Date + ti;
                //        outTime = toDateScale.DateTime;
                //        to = new TimeSpan(23, 59, 59);
                //        outTime = outTime.Date + to;
                //        this.Search(inTime, outTime);

                //        break;
                //}
                var listgroup = _scaleList.GroupBy(p => new { p.CustomerCode, P = p.ScaleTicketCode.Substring(6, 1) });
                foreach (var _vendorgroup in listgroup)
                {
                    list = _vendorgroup as IList<ScaleTicketDTO>;
                    ExportTicket(_vendorgroup.Key.P, _vendorgroup.Key.CustomerCode, _vendorgroup.Select(x => x));
                }
                Common.ShowSuccessful("Xuất Excel thành công!");
            }
            else
            {
                return;
            }
        }

        private void ExportTicket(string location, string customerCode, IEnumerable<ScaleTicketDTO> list)
        {
            string filename = string.Empty;

            // Export Excel file
            table.Rows.Clear();
           // list = list.Where(x => x.ScaleTicketCode.Substring(3, 1) == zero.ToString());
            int zero = 0;
            decimal tapchat2 = 0;
            if (list.Count() > 0)
            {
                foreach (var ticket in list)
                {
                    if (ticket.ActualWeight > 0)
                    {
                        zero = Convert.ToInt32(ticket.ScaleTicketCode.Substring(6, 1));
                        if (filename == string.Empty)
                            filename = String.Format("{0:yyyyMMdd}-{1}-{2}", ticket.OutHour, location, customerCode);
                        tapchat2 = Math.Round((ticket.ActualWeight - ticket.KgReduce) * ticket.PercentReduce / 100,2);
                        table.Rows.Add(new object[] {
                        //ticket.ScaleTicketCode,
                        //FontConversion.ConvertUnicode2VNI(ticket.RequireName),
                        //ticket.ItemNumber,
                        //FontConversion.ConvertUnicode2VNI(ticket.ItemName),
                        //ticket.CustomerCode,
                        //FontConversion.ConvertUnicode2VNI(ticket.CustomerName),
                        //ticket.InHour,
                        //ticket.OutHour,
                        //ticket.FirstWeight,
                        //ticket.SecondWeight,
                        //ticket.ActualWeight,
                        //ticket.VehicleID,
                        //ticket.LocationCode,
                        //ticket.Quantity1,
                        //FontConversion.ConvertUnicode2VNI(ticket.ItemUnit),
                        //ticket.Quantity2,
                        //FontConversion.ConvertUnicode2VNI(ticket.ItemUnit2),
                        //Math.Round((decimal)(ticket.Quantity2 > 0 ? ticket.Quantity1 / ticket.Quantity2 : ticket.Quantity1), 2)

                     
                        ticket.ScaleTicketCode,
                        ticket.RequireCode,
                        ticket.ItemNumber,                        
                        ticket.CustomerCode,
                        ticket.ActualWeight,
                       ticket.PercentReduce,
                       tapchat2,
                       Math.Round((decimal)ticket.KgReduce),
                        ticket.VehicleID,
                        ticket.LocationCode,
                       Convert.ToDecimal( ticket.Quantity1),
                        ticket.Quantity2,
                         ticket.Description,
                      ticket.RateDB,
                        FontConversion.ConvertUnicode2VNI(ticket.ItemUnit),                      
                       FontConversion.ConvertUnicode2VNI(ticket.ItemUnit2),                       
                        ticket.InHour,
                        ticket.OutHour,                       
                        Math.Round((decimal)ticket.FirstWeight),
                        Math.Round((decimal)ticket.SecondWeight),
                        FontConversion.ConvertUnicode2VNI(ticket.ItemName),
                        FontConversion.ConvertUnicode2VNI(ticket.CustomerName)
            
                        });
                    }
                }

                this.ExportToExcel(filename,zero);
            }
        }

        private void ExportToExcel(string filename,int zero)
        {
            try
            {

                //begin save Excel to storage Path
                string filelocation = String.Format("{0}/{1}/{2}.xls", Common.storagePath, zero, filename);

                if (File.Exists(filelocation))
                {
                    DialogResult result = MessageBox.Show("File này đã xuất Excel, bạn có muốn xóa đi và xuất lại không?", "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.No)
                        return;

                    File.Delete(filelocation);
                }

                //string[] headers = new string[] {
                //            "[Mã số phiếu cân] Text(100)",
                //            "[Số yêu cầu] Text(200)",
                //            "[Mã hàng hóa] Text(30)",
                //            "[Tên hàng hóa] Text(200)",
                //            "[Mã vendor] Text(30)",
                //            "[Tên vendor] Text(200)",
                //            "[Giờ xe vào] Date",
                //            "[Giờ xe ra] Date",
                //            "[Vào] Number",
                //            "[Ra] Number",
                //            "[Trọng lượng (kg)] Number",
                //            "[Số xe] Text(10)",
                //            "[Kho] Text(100)",
                //            "[Số lượng 1] Number",
                //            "[ĐVT 1] Text(30)",
                //            "[Số lượng 2] Number",
                //            "[ĐVT 2] Text(30)",
                //            "[Đơn trọng] Number"
                //        };

                //string[] headers = new string[] {
                //            "F1 Text(100)",
                //            "F2 Text(200)",
                //            "F3 Text(30)",
                //            "F4 Text(200)",
                //            "F5 Text(30)",
                //            "F6 Text(200)",
                //            "F7 Date",
                //            "F8 Date",
                //            "F9 Number",
                //            "F10 Number",
                //            "F11 Number",
                //            "F12 Text(10)",
                //            "F13 Text(100)",
                //            "F14 Number",
                //            "F15 Text(30)",
                //            "F16 Number",
                //            "F17 Text(30)",
                //            "F18 Number"
                //        };

                // ImportData.CreateExcelTable(filelocation, "Sheet1", headers);
                // ImportData.TableToExcel(filelocation, "Sheet1", table);

                //Create the data set and table
                DataSet ds = new DataSet("Sheet1");

                //Set the locale for each
                ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
                table.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
                table.TableName = "Sheet1";

                //Add the table to the data set
                ds.Tables.Add(table);

                ExcelLibrary.DataSetHelper.HDR = false;
                ExcelLibrary.DataSetHelper.CreateWorkbook(filelocation, ds);
                

                ds.Tables.Clear();
                ds.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnRemove_Click()
        {
            string pass = String.Empty;
            try
            {
                if (ClassInput.InputBox("Chú ý", "Nhập password để xóa phiếu cân", ref pass) == DialogResult.OK)
                    {
                        if (pass.ToUpper() == Common.passManualInput)
                        {
                            if (this.gridView1.GetFocusedRow() == null)
                            {
                                Common.ShowAlert("Bạn phải chọn một dòng để xóa.");
                                return;
                            }
                            _scale = this.gridView1.GetFocusedRow() as ScaleTicketDTO;
                            bool? result = Common.ShowYesNoQuestion("Bạn có chắc muốn xóa phiếu cân này?");
                            if (result.HasValue && result.Value)
                            {
                                bool r = _dataAccess.Delete(_scale);
                                if (r)
                                {
                                    this.gridView1.DeleteSelectedRows();
                                    this.gridView1.RefreshData();
                                }
                                else
                                {
                                    Common.ShowAlert("Quá trình xóa phiếu không thành công");
                                }
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                Common.ShowAlert("Lỗi xóa phiếu" + ex.Message);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            this.PrintMethod();
        }

        private void Search(DateTime inTime, DateTime outTime)
        {
            _dataAccess.SearchObject = new ScaleTicketDTO();
            _dataAccess.SearchObject.InHour = inTime;
            _dataAccess.SearchObject.OutHour = outTime;
            _dataAccess.SearchObject.VehicleID = txtVehicleID.Text;
            _dataAccess.SearchObject.CustomerName = txtCustomer.Text;
            _scaleList = _dataAccess.Search();
           // this.gridControlTickets.DataSource = _scaleList;
        }

        private void Search()
        {
            DateTime inTime = fromdateScale.DateTime;
            TimeSpan ti = new TimeSpan(0, 0, 0);
            inTime = inTime.Date + ti;
            DateTime outTime = toDateScale.DateTime;
            TimeSpan to = new TimeSpan(23, 59, 59);
            outTime = outTime.Date + to;
            _dataAccess.SearchObject = new ScaleTicketDTO();
            _dataAccess.SearchObject.InHour = inTime;
            _dataAccess.SearchObject.OutHour = outTime;
            _dataAccess.SearchObject.VehicleID = txtVehicleID.Text;
            _dataAccess.SearchObject.ScaleTicketCode = txtModelVehicleCode.Text;
            _dataAccess.SearchObject.CustomerName = txtCustomer.Text;
            _dataAccess.SearchObject.RequireName = txtRequireNumber.Text;
            _dataAccess.SearchObject.ItemName = txtItem.Text;
            _dataAccess.SearchObject.LocationCode = txtLocation.Text;
            _scaleList = _dataAccess.Search();
            this.gridControlTickets.DataSource = _scaleList;
        }

        private void PrintMethod()
        {
            ScaleTicketDTO ticket = this.gridView1.GetFocusedRow() as ScaleTicketDTO;
            ILocationDataAccess locationDA = new LocationDataAccess();
            var location = locationDA.Get(ticket.LocationCode);
            if (location != null)
                ticket.LocationName = location.LocationName;

            decimal rate;
            string scaleType = String.Empty;
            string scaleType2 = String.Empty;
            string selectType = String.Empty;
            string unit = String.Empty;
            decimal tapchat;
            selectType = ticket.ScaleTicketCode.Substring(0, 2);
            tapchat = Math.Round((ticket.ActualWeight - ticket.KgReduce) * (Convert.ToDecimal(ticket.PercentReduce))/100,2);
            switch (selectType)
            {
                case "PR":
                    scaleType = "NHẬP (PR)";
                    scaleType2 = "PR-";
                    break;
                case "CI":
                    scaleType = "XUẤT SỬ DỤNG (CI)";
                    scaleType2 = "CI-";
                    break;
                case "SI":
                    scaleType = "XUẤT BÁN (SI)";
                    scaleType2 = "SI-";
                    break;
                case "TR":
                    scaleType = "CHUYỂN (NHẬP: TR)";
                    scaleType2 = "TR-";
                    break;
                case "TI":
                    scaleType = "CHUYỂN (XUẤT: TI)";
                    scaleType2 = "TI-";
                    break;
            }
            unit = ticket.ScaleTicketCode.Substring(6, 1);
            try
            {

                ReportDocument report = new ReportDocument();
                report.Load(Application.StartupPath + @"\Reports\crtScaleTicket.rpt");
                report.SetDataSource(CollectionExtensions<ScaleTicketDTO>.ConvertToDataTable(new List<ScaleTicketDTO>() { ticket }, "ScaleTicket"));
                if (ticket.Quantity2 == 0)
                {
                    rate = 0;
                }
                else
                {
                    rate = Math.Round(Convert.ToDecimal(ticket.Quantity1) / Convert.ToDecimal(ticket.Quantity2), 2);
                }
                report.SetParameterValue("weightRate", rate);
                report.SetParameterValue("ScaleType", scaleType);
                report.SetParameterValue("Unit", unit);
                report.SetParameterValue("typeScale", scaleType2);
                report.SetParameterValue("tapchat", tapchat);
                SettingApp setting = new SettingApp();

                if (Common.CheckPrinter(setting.ReceiptPrintName))
                    report.PrintOptions.PrinterName = setting.ReceiptPrintName;
                report.PrintOptions.ApplyPageMargins(new CrystalDecisions.Shared.PageMargins(setting.MarginLeft, setting.MarginTop, setting.MarginRight, setting.MarginBottom));

                if (setting.IsPreviewReceiptPrint)
                {
                    FormPrintPreview form = new FormPrintPreview(report);
                    form.ShowDialog();
                }
                else
                {
                    report.PrintToPrinter(1, false, 0, 0);
                }
            }
            catch (Exception ex)
            {
                Common.ShowAlert(ex.Message);
            }
        }
        #endregion

        #region Events
        protected override void OnEvents()
        {
            this.btnClose.Click += new EventHandler(delegate { this.Close(); });
            this.Disposed += new EventHandler(delegate { instance = null; });
            this.btnSearch.Click += new EventHandler(btnSearch_Click);
            this.btnReset.Click += new EventHandler(btnReset_Click);
            this.btnRemove.Click += new EventHandler(delegate { btnRemove_Click(); });
            this.btnPrint.Click += new EventHandler(btnPrint_Click);
            this.btnExportExcel.Click += new EventHandler(btnExportExcel_Click);
            this.chkRequire.CheckedChanged += new EventHandler(chkRequire_CheckedChanged);
            base.OnEvents();
        }

        void chkRequire_CheckedChanged(object sender, EventArgs e)
        {
            if (chkRequire.Checked)
            {
                this.groupBoxExportOrder.Visible = true;
            }
            else
            {
                this.groupBoxExportOrder.Visible = false;
            }
        }

     
        protected override void OnLoad(EventArgs e)
        {
            this.fromdateScale.DateTime = DateTime.Now;
            this.toDateScale.DateTime = DateTime.Now;
            this.Search();
            base.OnLoad(e);
            // Init table
            //table.Columns.Add("TicketID", typeof(string));
            //table.Columns.Add("Requirement", typeof(string));
            //table.Columns.Add("ItemNumber", typeof(string));
            //table.Columns.Add("ItemName", typeof(string));
            //table.Columns.Add("VendorID", typeof(string));
            //table.Columns.Add("VendorName", typeof(string));
            //table.Columns.Add("InTime", typeof(DateTime));
            //table.Columns.Add("OutTime", typeof(DateTime));
            //table.Columns.Add("Weight1", typeof(decimal));
            //table.Columns.Add("Weight2", typeof(decimal));
            //table.Columns.Add("BalanceWeight", typeof(decimal));
            //table.Columns.Add("VehicleNumber", typeof(string));
            //table.Columns.Add("LocationID", typeof(string));
            //table.Columns.Add("Qty1", typeof(decimal));
            //table.Columns.Add("Unit1", typeof(string));
            //table.Columns.Add("Qty2", typeof(decimal));
            //table.Columns.Add("Unit2", typeof(string));
            //table.Columns.Add("QtyPct", typeof(decimal));

            //chinh sua 01/02/2013
            //table.Columns.Add("TicketID", typeof(string));
            //table.Columns.Add("Requirement", typeof(string));
            //table.Columns.Add("ItemNumber", typeof(string));
            //table.Columns.Add("VendorID", typeof(string));
            //table.Columns.Add("BalanceWeight", typeof(decimal));
            //table.Columns.Add("PercentDuty", typeof(decimal)); //% tap chat
            //table.Columns.Add("Duty", typeof(decimal));
            //table.Columns.Add("VehicleNumber", typeof(string));
            //table.Columns.Add("LocationID", typeof(string));
            //table.Columns.Add("Qty1", typeof(decimal));
            //table.Columns.Add("Unit1", typeof(string));
            //table.Columns.Add("Qty2", typeof(decimal));
            //table.Columns.Add("Unit2", typeof(string));
            //table.Columns.Add("Description", typeof(string));//dien giai
            //table.Columns.Add("InTime", typeof(DateTime));
            //table.Columns.Add("OutTime", typeof(DateTime));
            //table.Columns.Add("MinusKG", typeof(decimal)); //so kg tru khac
            //table.Columns.Add("Weight1", typeof(decimal));
            //table.Columns.Add("Weight2", typeof(decimal));

            //table.Columns.Add("ItemName", typeof(string));
            //table.Columns.Add("VendorName", typeof(string));


            // chinh ngay 5/2/2013
            // Init table 
            table.Columns.Add("TicketID", typeof(string));
            table.Columns.Add("Requirement", typeof(string));
            table.Columns.Add("ItemNumber", typeof(string));
            table.Columns.Add("VendorID", typeof(string));
            table.Columns.Add("BalanceWeight", typeof(decimal));
            table.Columns.Add("PercentDuty", typeof(decimal)); //% tap chat
            table.Columns.Add("Duty", typeof(decimal));
            table.Columns.Add("MinusKG", typeof(decimal)); //so kg tru khac
            table.Columns.Add("VehicleNumber", typeof(string));
            table.Columns.Add("LocationID", typeof(string));
            table.Columns.Add("Qty1", typeof(decimal));
            table.Columns.Add("Qty2", typeof(decimal));
            table.Columns.Add("Description", typeof(string));//dien giai
            table.Columns.Add("Rate", typeof(decimal)); // don trong
            table.Columns.Add("Unit1", typeof(string));
            table.Columns.Add("Unit2", typeof(string));
            table.Columns.Add("InTime", typeof(DateTime));
            table.Columns.Add("OutTime", typeof(DateTime));
            
            table.Columns.Add("Weight1", typeof(decimal));
            table.Columns.Add("Weight2", typeof(decimal));

            table.Columns.Add("ItemName", typeof(string));
            table.Columns.Add("VendorName", typeof(string));   
        }

        #endregion

       

    }
}
